# coding:utf-8
import urllib;
import urllib2;
import cookielib;
import base64;
import hashlib;
import time;
import json;
import re;
import rsa;
import binascii;
import zlib;
import sys;



postdata = {
    'encoding':'UTF-8',
    'entry':'weibo',
    'from':'',
    'gateway':'1',
    'nonce':'',
    'pagerefer':'',
    'prelt':'107',
    'pwencode':'rsa2',
    'returntype':'META',
    'rsakv':'',
    'savestate':'7',
    'servertime':'',
    'service':'miniblog',
    'sp':'',
    'su':'',
    'url':'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack',
    'useticket':'1',
    'vsnf':'1'
}

class loginSina:
    
    def __init__(self):
        self.cookie = cookielib.CookieJar();
        self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie));
        self.userInfo = None;
        
    def login(self, username, passwd):
            
        "获取到 servertime 和 nonce"
        
        s_dict = self.getServerTimeAndNonce(username);
        
        
        "用戶名加密"
        
        u = self.userNamebase64(username);
        
        "密码加密"
        rsaPublickey = int(s_dict["pubkey"], 16);
        key = rsa.PublicKey(rsaPublickey, 65537);
        message = str(s_dict["servertime"]) + '\t' + str(s_dict["nonce"]) + '\n' + str(passwd);
        
        passwd = rsa.encrypt(message, key);
        
        passwd = binascii.b2a_hex(passwd);
        
        postdata["servertime"] = s_dict["servertime"];
        postdata["nonce"] = s_dict["nonce"];
        postdata["rsakv"] = s_dict["rsakv"];
        postdata["su"] = u;
        postdata["sp"] = passwd;
        
        url = "http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.5)";
        
        p = urllib.urlencode(postdata);
        
        request = urllib2.Request(url, p);
        
        response = self.opener.open(request);
        
        str_html = response.read();
        
        re1 = re.compile(r'[\s\S]*?&retcode=([\s\S]*?)&[\s\S]*?', re.IGNORECASE);
        
        m1 = re.match(re1, str_html);
        
        flag = -1;
        
        if(m1):
            flag = int(m1.group(1));
            if(flag == 0):
                print "login success";
            else:
                print "login fail";
        if(flag == 0):
            re2 = re.compile(r'[\s\S]*?location.replace\(\"([\s\S]*?)\"\)[\s\S]*?', re.IGNORECASE);
            m2 = re.match(re2, str_html);
            if(m2):
                return m2.group(1);
            else:
                return "";
        else:
            return "";        
        
        pass
    
    def loginReplace(self, url):
        request = urllib2.Request(url);
        response = self.opener.open(request);
        
        str_html = response.read();
        
        repattern = re.compile(r'[\s\S]*?\(([\s\S]*?)\)[\s\S]*?', re.IGNORECASE);
        m = re.match(repattern, str_html);
        if(m):
            str_json = m.group(1);
            s_dict = json.loads(str_json);
            self.userInfo = s_dict;
    
    """
    到主頁，根据需求来分析事物
    """
    def loginIndex(self):
        tmpurl = "http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack&sudaref=weibo.com";
        request = urllib2.Request(tmpurl);
        response = self.opener.open(request);
        # print response.read();
        
        url = "http://weibo.com/%s" % self.userInfo["userinfo"]["userdomain"];
        request = urllib2.Request(url);
        response = self.opener.open(request);
#         s_html = response.read();
        
    
    def getServerTimeAndNonce(self, username):
        
        url1 = "http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su=%s&rsakt=mod&client=ssologin.js(v1.4.5)&_=%s" % (username, str(int(time.time())));
        
        "首先获取一些基本信息"
        
        requset = urllib2.Request(url1);
        
        response = self.opener.open(requset);
        
        str_json = response.read();
        
        "通过正则来获取json字符串"
        
        pattern = re.compile(r'[\s\S]*?\(([\s\S]*?)\)', re.IGNORECASE);
        
        match = re.match(pattern, str_json);
        
        if(match):
            s_json = match.group(1);
            
            s_dict = json.loads(s_json);
            
            return s_dict;
            
        else:
            return None;
        
        pass
        
    
    """
    用户名base64加密
    """
    def userNamebase64(self, username):
        
        un = urllib.quote(username);
        
        uname = base64.encodestring(un)[:-1];
        
        return uname.strip();
        
        pass
    
    """
    用SHA1加密密码
    """
    def SHA1Passwd(self, passwd):
        
        return hashlib.sha1(passwd).hexdigest();
        
        pass
    
    def Mali(self):
        
        url = "http://e.weibo.com/1928277187/app_3759261442?key=CG";
        
        request = urllib2.Request(url);
        
        response = self.opener.open(request);
        
        str_html = response.read();
        
        rp = re.compile(r'[\s\S]*?<script>([\s\S]*?)</script>[\s\S]*?', re.IGNORECASE);
        
        mu = re.findall(rp, str_html);
        
        m_dict = None;
        
        for ms in mu:
            fi = ms.find('(');
            s_json = ms[fi + 1:-1];
            s_dict = json.loads(s_json);
            if('pid' in s_dict):
                if(s_dict['pid'] == 'pl_apps_thirdapp'):
                    m_dict = s_dict;
                    break;
                
        if(m_dict):
            
            "得到appurl地址"
            
            html = m_dict['html'];
            
            rp = re.compile(r'[\s\S]*?src=\"([\s\S]*?)\"[\s\S]*?', re.IGNORECASE);
            
            m = re.match(rp, html);
            
            if(m):
                urlApp = m.group(1);
                
                rq = urllib2.Request(urlApp);
                rs = self.opener.open(rq);
                
                str_html = rs.read();
                
                "获取cid,sub_appkey,viewer,token"
                
                pr1 = re.compile(r'[\s\S]*?\"oauth_token\":\"([\s\S]*?)\"[\s\S]*?', re.IGNORECASE);
                m = re.match(pr1, str_html);
                if(m):
                    str_token = m.group(1);
                    print "token:", str_token;
                
                pr2 = re.compile(r'[\s\S]*?cid=([\S\s]*?)[&;][\s\S]*?', re.IGNORECASE);
                m = re.match(pr2, str_html);
                if(m):
                    str_cid = m.group(1);
                    print "cid:", str_cid;
                    
                pr3 = re.compile(r'[\s\S]*?sub_appkey=([\S\s]*?)[&;][\s\S]*?', re.IGNORECASE);
                m = re.match(pr3, str_html);
                if(m):
                    sub_appkey = m.group(1);
                    print "sub_appkey:", sub_appkey;
                
                pr4 = re.compile(r'[\s\S]*?viewer=([\S\s]*?)[&;][\s\S]*?', re.IGNORECASE);
                m1 = re.match(pr4, str_html);
                if(m1):
                    str_viewer = m1.group(1);
                    print "viewer:", str_viewer;
                
                pr5 = re.compile(r'[\s\S]*?Play.aspx([\S\s]*?)[\"][\s\S]*?', re.IGNORECASE);
                m1 = re.match(pr5, str_html);
                if(m1):
                    str_referer = "http://www.mariedalgar.com/games/heiliusu/index.aspx" + m1.group(1).replace("amp;","");
                    str_referer = urllib.quote(str_referer,safe='');
                    print "referer:", str_referer;
                
                "访问一个中间"
                
                murl = "https://api.weibo.com/oauth2/xd.jsp?"+\
                    "appkey=%s&access_token=%s&referer=%s&" %(sub_appkey,str_token,str_referer);
                    
                trq = urllib2.Request(murl);
                trs = self.opener.open(trq);                
                
                purl1 = "https://api.weibo.com/2/statuses/upload_url_text.json";
                
                pd ={
                     '_cache_time':'0',
                     'access_token':str_token,
                     'method':'post',
                     'source':sub_appkey,
                     'url':'http://www.mariedalgar.com/games/Heiliusu/images/Share/pass.jpg',
                     'status':'美睫逆生长的惊天秘密被我发现啦！原来这美睫的秘密就藏在玛丽黛佳黑流苏密语睫毛膏中，想一探究竟，那就赶紧登录 http://www.mariedalgar.com/10000/ 和流苏小姐一起开启一段神秘的解码黑流苏之旅吧,更有10000支黑流苏等你来拿哦~~'
                };
                
                hders = {
                           'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:20.0) Gecko/20100101 Firefox/20.0',
                           'referer':murl,
                };
                
                
                ptd = urllib.urlencode(pd);
                try:
                    
                    rqw = urllib2.Request(purl1,ptd,headers=hders);               
                    rsw = self.opener.open(rqw);
                    
                    str_j1 = rsw.read();
                    
                except urllib2.HTTPError as http_error:
                    
                    userurl = "https://api.weibo.com/2/users/show.json?"+\
                        "access_token=%s&uid=%s&_cache_time=30&method=get&__rnd=%s"%(str_token,str_viewer,str(int(time.time())))
                    
                    userq = urllib2.Request(userurl);
                    users = self.opener.open(userq);
                    
                    str_j1 = users.read();
                    
                    #str_j1 =  http_error.read();
                    
                    pass
                
                print "text:", str_j1;
                
                "friendshow"
                
                friendurl = "https://api.weibo.com/2/friendships/show.json?"+\
                    "access_token=%s&source_id=%s&target_id=%s&source=%s&_cache_time=30&method=get&__rnd=%s"%(str_token,str_viewer,str_cid,sub_appkey,str(int(time.time())));
                
                rqfriend = urllib2.Request(friendurl);
                rsfriend = self.opener.open(rqfriend);
                
                str_j2 = rsfriend.read();
                
                print "freend:", str_j2;
                
                paramterdict = {
                                'access_token':str_token,
                                'source_id':str_viewer,
                                'target_id':str_cid,
                                };
                str_paramter = json.dumps(paramterdict);
                
                plog = {
                        'operation':urllib.quote('/friendships/show.json',safe=''),
                        'parameters':urllib.quote(str_paramter,safe=''),
                        'result':urllib.quote(str_j1,safe=''),
                        'successful':'true',
                        'uid':str_viewer
                };
                
                ploghead = {
                            'Content-Type':'application/json',
                };
                
                plogurl = "http://www.mariedalgar.com/games/heiliusu/WebService.asmx/LogOperation";
                
                plogdata = json.dumps(plog);
                
                plogrq = urllib2.Request(plogurl,plogdata,ploghead);
                
                plogrs = self.opener.open(plogrq);
                
                print "code:", plogrs.read();
                
                "获取地址信息"
                
                addressurl = "http://www.mariedalgar.com/games/heiliusu/WebService.asmx/GetCustomerInfo";
                addict =  {
                           'uid':str_viewer
                           };
                adddata = json.dumps(addict);
                
                addresshead = {
                               'Content-Type':'application/json',
                               };
                               
                addressq = urllib2.Request(addressurl,adddata,addresshead);
                
                addressr = self.opener.open(addressq);
                
                address_str = addressr.read();
                
                addressDict = json.loads(address_str);
                
                print "adress:", str(addressDict);
                
                lotterurl = "http://www.mariedalgar.com/games/heiliusu/webservice.asmx/EnableLottery2";
                lotterdict={
                            'address':urllib.quote(str(addressDict['d']["Address"]),safe=''),
                            'city':urllib.quote(str(addressDict['d']["City"]),safe=''),
                            'district':urllib.quote(str(addressDict['d']["District"]),safe=''),
                            'email':urllib.quote(str(addressDict['d']["Email"]),safe=''),
                            'name':urllib.quote(str(addressDict['d']["Name"]),safe=''),
                            'province':urllib.quote(str(addressDict['d']["Province"]),safe=''),
                            'tel':urllib.quote(str(addressDict['d']["Tel"]),safe=''),
                            'uid':str_viewer,
                            'weibo':urllib.quote("微博壞脾气",safe=''),
                            'p1':'162',
                            'p2':'258',
                            'p3':'395',
                            };
                lotterpost = json.dumps(lotterdict);
                lotterhead={
                            'Content-Type':'application/json',
                            };
                lottersq = urllib2.Request(lotterurl,lotterpost,lotterhead);
                lotterrs = self.opener.open(lottersq);
                
                print "lotterfrist:",lotterrs.read();
                
                lotterendurl = "http://www.mariedalgar.com/games/heiliusu/WebService.asmx/Lottery";
                lotterenddict = {'uid':str_viewer};
                lotterendpost = json.dumps(lotterenddict);
                lotterendhead={'Content-Type':'application/json'};
                
                lotterendsq = urllib2.Request(lotterendurl,lotterendpost,lotterendhead);
                lotterendsr = self.opener.open(lotterendsq);
                
                print "lotter:",lotterendsr.read();
                                   
            
            pass
    
        pass    

if(__name__ == "__main__"):
    
    ls = loginSina();
    url = ls.login("janey3368@sina.com", "881122");
    
    if(len(url) > 0):
        ls.loginReplace(url);
        ls.loginIndex();
        
        sys.stdout.write("输入Ctrl+C退出...")
        
        while(True):
            
            ls.Mali();
            
            time.sleep(1);
            
            pass
        
    else:
        print "login fail";
     
    pass
